package util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class MysqlUtil {

    static String DRIVER;
    static String URL;
    static String USER;
    static String PASSWORD;

    static Connection connection=null;
    static PreparedStatement ps=null;
    static ResultSet rs=null;

    static {
        //1、通过反射加载驱动
        try {
            //操作配置文件中的信息
            Properties properties = new Properties();

            //反射加载配置文件
            InputStream is = Res.class.getClassLoader().getResourceAsStream("mysql.properties");

            //使用properties对象加载输入流
            properties.load(is);
            DRIVER = properties.getProperty("driver");
            URL = properties.getProperty("url");
            USER = properties.getProperty("username");
            PASSWORD = properties.getProperty("password");
            Class.forName(DRIVER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getCon(){

        //2、建立连接
        try {
            connection= DriverManager.
                   getConnection(URL,
                           USER,
                           PASSWORD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return connection;
    }


    public static PreparedStatement getPs(String sql){


        try {
            ps= connection.prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return ps;
    }

    public static ResultSet getRs(){


        try {
            rs= ps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;

    }

    //增删改
    public static int getInsert(){

        int i = 0;
        try {
            i = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return i;

    }

    public static void close(){

        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (ps!=null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}
